package org.dromara.websocket.connection;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.commons.lang3.StringUtils;

import java.net.InetSocketAddress;

/**
 * Created by       PokerFace
 * Create Date      2023-09-28
 * Email:
 * Version          1.0.0
 * <p>
 * Description:
 */
public class Connection {

    /**
     * 连接一参数
     */
    protected Channel channel;

    /**
     * 是否连接成功
     */
    protected volatile boolean connected;


    Connection(ChannelHandlerContext context) {
        this.channel = context.channel();
        this.connected = true;
    }


    /**
     * get remote host address
     *
     * @return host address
     */
    public String getRemoteHostAddress() {

        InetSocketAddress socketAddress = (InetSocketAddress) channel.remoteAddress();
        return socketAddress.getAddress().getHostAddress();
    }


    public int getRemotePort() {
        InetSocketAddress socketAddress = (InetSocketAddress) channel.remoteAddress();
        return socketAddress.getPort();
    }


    public Channel getChannel() {
        return channel;
    }


    public boolean isConnected() {
        return channel != null && channel.isActive();
    }


    /**
     * 推送json
     *
     * @param object
     */
    public void push(Object object) {
        if (object instanceof JSONObject) {
            push(((JSONObject) object).toJSONString());
        } else if (object instanceof JSONArray) {
            push(((JSONArray) object).toJSONString());
        } else if (object instanceof String) {
            push((String) object);
        } else {
            push(JSONObject.toJSONString(object));
        }
    }

    /**
     * 推送json
     *
     * @param content
     */
    public void push(String content) {
        if (!isConnected() || StringUtils.isEmpty(content)) return;
        channel.writeAndFlush(new TextWebSocketFrame(content));
    }


}
